﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Device.Location;
using System.Diagnostics;

namespace Theosoft.Mobile.LibService
{
    public class PositionTask
    {
        private static GeoCoordinateWatcher mywatcher = null;

        public EventHandler<objEventArgs> Completed { get; set; }

        public void getLocation()
        {
            mywatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
            mywatcher.MovementThreshold = 20.0;
            mywatcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(MyPositionChanged);
            mywatcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(MyStatusChanged);
            mywatcher.Start();
        }

        private void MyPositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            Debug.WriteLine("GPS position changed.");
            mywatcher.Stop();
            mywatcher.Dispose();
            mywatcher = null;

            this.Completed.Invoke(this, new objEventArgs(e.Position.Location));
        }

        private void MyStatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            switch (e.Status)
            {
                case GeoPositionStatus.Disabled:
                    Debug.WriteLine("Location service is disabled!");
                    this.Completed.Invoke(this, new objEventArgs(new GeoCoordinate(0, 0)));
                    break;

                case GeoPositionStatus.Initializing:
                case GeoPositionStatus.NoData:
                case GeoPositionStatus.Ready:
                    Debug.WriteLine("GPS {0}.", e.Status);
                    break;

                default:
                    Debug.WriteLine("GPS status changed.");
                    return;
            }
        }
    }
}
